package com.wuzhun.wxmp.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.wuzhun.wxmp.annotation.PageLoginRequired;
import com.wuzhun.wxmp.common.Result;
import com.wuzhun.wxmp.controller.BaseController;
import com.wuzhun.wxmp.model.dto.MessageDTO;
import com.wuzhun.wxmp.model.dto.WechatDTO;
import com.wuzhun.wxmp.model.dto.admin.MessageCountDTO;
import com.wuzhun.wxmp.model.dto.admin.YearCountDTO;
import com.wuzhun.wxmp.model.entity.Message;
import com.wuzhun.wxmp.model.excel.MessageData;
import com.wuzhun.wxmp.service.IMessageService;
import com.wuzhun.wxmp.service.IWechatService;
import com.wuzhun.wxmp.util.DateTimeUtil;
import com.wuzhun.wxmp.util.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 微信公众号表 前端控制器
 * </p>
 *
 * @author renbaolin
 * @since 2022-12-03
 */
@Controller
@RequestMapping("/admin/message")
public class AdminMessageController extends BaseController {

    @Resource
    private IMessageService messageService;
    @Resource
    private IWechatService wechatService;
    @Value("${wuzhun.domain}")
    private String domain;

    @GetMapping("")
    @ApiOperation("消息列表页面")
    @PageLoginRequired
    public ModelAndView index(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                              @RequestParam(value = "pageSize", required = false, defaultValue = "15") Integer pageSize,
                              @RequestParam(name = "mpId", required = false) String mpId,
                              @RequestParam(name = "keyword", required = false) String keyword,
                              @RequestParam(name = "startDate", required = false) String startDate,
                              @RequestParam(name = "endDate", required = false) String endDate) {
        ModelAndView modelAndView = new ModelAndView();
        Page<Message> pageMessage = new Page<>();
        pageMessage.setCurrent(page);
        pageMessage.setSize(pageSize);
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(mpId)) {
            queryWrapper.eq("mp_id", mpId);
        }
        modelAndView.addObject("mpId", mpId);
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("content", keyword);
        }
        modelAndView.addObject("keyword", keyword);
        if (StringUtils.isNotEmpty(startDate)) {
            queryWrapper.ge("created_time", DateTimeUtil.string2Date(startDate + " 00:00:00"));
        }
        modelAndView.addObject("startDate", startDate);
        if (StringUtils.isNotEmpty(endDate)) {
            queryWrapper.le("created_time", DateTimeUtil.string2Date(endDate + " 23:59:59"));
        }
        modelAndView.addObject("endDate", endDate);
        queryWrapper.select("any_value(id) as id", "any_value(mp_id) as mp_id", "any_value(content) as content", "any_value(created_time) as created_time", "wx_user_id", "LEFT(created_time, 10) as send_day").groupBy(Arrays.asList("wx_user_id", "send_day")).orderByDesc("created_time");
        Page<MessageDTO> messageDTOPage = messageService.listByPage(pageMessage, queryWrapper);
        modelAndView.addObject("pageData", messageDTOPage);
        modelAndView.addObject("wechatList", wechatService.queryList());
        return commonView(modelAndView, "admin/message/index");
    }

    @GetMapping("/count")
    @ApiOperation("消息统计页面")
    @PageLoginRequired
    public ModelAndView count() {
        List<WechatDTO> wechatDTOList = wechatService.queryList();
        List<Message> messageYearList = messageService.list(new QueryWrapper<Message>().select("DISTINCT year").orderByDesc("year"));
        List<MessageCountDTO> messageCountList = Lists.newArrayListWithCapacity(wechatDTOList.size());
        for (WechatDTO wechatDTO : wechatDTOList) {
            MessageCountDTO messageCountDTO = new MessageCountDTO();
            messageCountDTO.setDepartment(wechatDTO.getDepartment());
            messageCountDTO.setMpName(wechatDTO.getName());
            List<YearCountDTO> yearCountList = Lists.newArrayListWithCapacity(messageYearList.size());
            for (Message message : messageYearList) {
                QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("mp_id", wechatDTO.getMpId());
                queryWrapper.eq("year", message.getYear());
                queryWrapper.select("DISTINCT wx_user_id");
                //queryWrapper.groupBy("wx_user_id");
                long count = messageService.count(queryWrapper);
                YearCountDTO yearCountDTO = new YearCountDTO();
                yearCountDTO.setCount(count);
                yearCountDTO.setYear(message.getYear());
                yearCountList.add(yearCountDTO);
            }
            messageCountDTO.setYearList(yearCountList);
            QueryWrapper<Message> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("mp_id", wechatDTO.getMpId());
            queryWrapper2.ge("created_time", DateTimeUtil.getStartTimeOfCurrentMonth(null));
            queryWrapper2.le("created_time", DateTimeUtil.getEndTimeOfCurrentMonth(null));
            queryWrapper2.select("DISTINCT wx_user_id");
            //queryWrapper2.groupBy("wx_user_id");
            long currentMonthCount = messageService.count(queryWrapper2);
            messageCountDTO.setCurrentMonthCount(currentMonthCount);
            messageCountList.add(messageCountDTO);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("currentYear", String.valueOf(DateTimeUtil.getCurrentYear()));
        modelAndView.addObject("messageCountList", messageCountList);
        modelAndView.addObject("messageYearList", messageYearList);
        return commonView(modelAndView, "admin/message/count");
    }

    @GetMapping("detail")
    @ApiOperation("消息详情页面")
    @ResponseBody
    @PageLoginRequired
    public Result detail(@RequestParam("id") Integer id) {
        Message message = messageService.getById(id);
        return new Result(message);
    }

    @GetMapping("/day/detail")
    @ApiOperation("查询用户消息详情")
    @ResponseBody
    @PageLoginRequired
    public Result dayDetail(@RequestParam("wxUserId") String wxUserId,
                            @RequestParam("startDate") String startDate,
                            @RequestParam("endDate") String endDate) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wx_user_id", wxUserId);
        queryWrapper.ge("created_time", DateTimeUtil.string2Date(startDate));
        queryWrapper.le("created_time", DateTimeUtil.string2Date(endDate));
        List<MessageDTO> messageList = messageService.queryListWrapper(queryWrapper);
        return new Result(messageList);
    }

    @GetMapping("/export-data")
    @ApiOperation("到处消息列表页面")
    @PageLoginRequired
    public void exportData(HttpServletResponse response) throws Exception {
        String fileName = "微信公众号收到消息列表" + DateTimeUtil.getYearMonthDay(null) ;
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), MessageData.class).sheet("消息列表").registerWriteHandler(ExcelUtil.cellBorder()).doWrite(getAllData());
    }

    /**
     * 分页查询所有消息列表
     *
     * @return
     */
    private List<MessageData> getAllData() {
        List<MessageDTO> messageDTOList = Lists.newLinkedList();
        Page<Message> pageMessage = new Page<>();
        pageMessage.setSize(50);
        QueryWrapper<Message> queryWrapper = new QueryWrapper<Message>().lt("id", Integer.MAX_VALUE).orderByDesc("created_time");
        while (true) {
            Page<MessageDTO> messageDTOPage = messageService.listByPage(pageMessage, queryWrapper);
            if (messageDTOPage == null || CollectionUtils.isEmpty(messageDTOPage.getRecords())) {
                break;
            }
            messageDTOList.addAll(messageDTOPage.getRecords());
            queryWrapper = new QueryWrapper<Message>().lt("id", messageDTOPage.getRecords().get(messageDTOPage.getRecords().size() -1 ).getId()).orderByDesc("created_time");
        }
        List<MessageData> messageDataList = Lists.newArrayListWithCapacity(messageDTOList.size());
        messageDTOList.forEach(messageDTO -> {
            MessageData messageData = new MessageData();
            BeanUtils.copyProperties(messageDTO, messageData);
            if (!Objects.equals("text", messageDTO.getMsgType())) {
                messageData.setContent(domain + messageData.getContent());
            }
            messageDataList.add(messageData);
        });
        return messageDataList;
    }
}
